#CREATE TABLE wua (rdb float,u float,val float);
from scipy import exp
import sqlite3
from scipy import integrate

import random

def generaRangordB(nf=4, mf=10):
  b = []
  for i in range(0, nf):
    for j in range(1, mf):
      b.append( j/10.0**(3-i) )
  return ( b )
  
def generaRangoLog(li, lf, n):
  """
  Genera intervalos equilog 

  La decripcion larga

  Parameters
  -----------------
  li : float
    Limite inferior
  lf : float
    Limite superior      
  n : float
    Nuero de intervalos en el rango
  """    
  # from math import *
  b = []
  kk = ( lf/li )**(1.0/n)
  for i in range(0, n+1):
    b.append( li*kk**i )
  return ( b )      

def Fua(x, a):
  """
  Funcion para integracion en acuifero semiconfinado

  La decripcion larga

  Parameters
  -----------------
  x : double
    Abscisa.
  """
  return (1/x*exp(-x-a*a/(4*x)))

def encuentraWuaD(c, rdb, u):  
  sql = "SELECT DISTINCT u,val FROM wua WHERE rdb=%f AND u<=%f ORDER BY u DESC;" % ( rdb, u )
  c.execute(sql)
  mrow = c.next()
  if mrow:
    um = mrow[0]
    wuam = mrow[1]  
 #print "Menor - a = %f, u= %f, uu = %f, valor = %f" % ( rdb, u,  mrow[0], mrow[1] ) 
  sql = "SELECT DISTINCT u,val FROM wua WHERE rdb=%f AND u>=%f ORDER BY u;" % ( rdb, u )
  c.execute(sql)
  Mrow = c.next()
  if Mrow:
    uM = Mrow[0]
    wuaM = Mrow[1]  
 #print "Mayor - a = %f, u= %f, uu = %f, valor = %f" % ( rdb, u,  Mrow[0], Mrow[1] )
  val = mrow[1] + ( u - mrow[0] )*( Mrow[1] - mrow[1] )/( Mrow[0] - mrow[0] )
 #print val 
  return ( val )

def limites(u):
  # Con regex?????
  n = None
  e = None
  es = None
  s = "%.2E" % u
  # 1.23E-12
  n = int ( s[0] )
  e = int ( s[5:] )
  if n == 9:
    es = e + 1
#    if e >= 0:
#      es = e - 1
#    else:
#      es = e + 1
  else:
    es = e
 #print "u=%f,n=%f,e=%f,es=%f" % (u, n, e, es)
  return ( [n, e, es] )

#def limites(expf):
#  if expf[0] == 9:
#    e = expf[1]
#    
#  li = "%.9f" % 
#  ls = 
#  return 

def encuentraWua(wuadata, rdb = '0.020', u = 0.0002573):
  vi = None
  vf = None
  valor = None
  
  # Capturo los limites
  ll = limites(u)
  limi = "%.10f" % ( ll[0]*10**ll[1] )
  limf = "%.10f" % ( ( ll[0] + 1 )*10**ll[2] )
 #print "\tlimi=%s,limf=%s" % (limi, limf)
  
  if  limi in wuadata[rdb].keys(): 
    vi = wuadata[rdb][limi]
   #print "\tvi = %s" % vi    
  
  if limf in wuadata[rdb].keys():
    vf = wuadata[rdb][limf]
   #print "\tvf = %s" % vf
  
  ## No hay datos el valor es muy bajo
  if not vi and not vf:
    return ( 0.000001 )
  
  ## Algun dato hay por eso estoy aqui
  if vi and vf:
    if abs(vi-vf)<= 0.0001:
      valor = vi
    else:
      valor = vi + ( u - float(limi) )*( vf - vi )/( float(limf) - float(limi) )
  else:
    if vi:
      valor = vi
    else:
      valor = vf
 #print "\tValor=%f" % valor
  return ( valor )    
  
def diez():
    global wuadata
    for a in range(0, 10000):
      rdb = '0.030'
      u = random.randrange(1000.0)/10000.0
      valor = encuentraWua(wuadata, rdb, u)      

def generaWua():
  ## r/B
  rdB = [0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5]
  temp = [0.000000001, 0.000000002, 0.000000003, 0.000000004, 0.000000005, 0.000000006, 0.000000007, 0.000000008, 0.000000009]
  ## valores de u para la W(u,rdB)
  uu = []
  for ex in range(0,11):
    for i in range(0,9):
      uu.append( temp[i]*10**ex )
  # El diccionario con los datos
  wuadata = {}
  for a in rdB:
    uval = {}
    aa = "%.3f" % round(a, 4)
    for u in uu:
      i = integrate.quad( Fua,u,integrate.Inf,args=(a) )
      v = "%.10f" % round(u, 10)
      if i[0] >=0.0001:
        uval[v] = i[0]
    wuadata[aa] = uval
  return ( wuadata )

def generaWuaMM():
  conn = sqlite3.connect('data.sqlite')
  c = conn.cursor()
  # rdB = generaRangoLog(0.001, 2.5, 41)
  rdB = [0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5]
  temp = [0.000000001, 0.000000002, 0.000000003, 0.000000004, 0.000000005, 0.000000006, 0.000000007, 0.000000008, 0.000000009]
  uu = []
  for ex in range(0,11):
    for i in range(0,9):
      uu.append( temp[i]*10**ex )
  ##print "u=%s" % uu   
  # uu = generaRangoLog(0.000000001, 50, 50)
  c.execute("DELETE FROM wua;")
  # global wuadata
  wuadata = {}
  for a in rdB:
    uval = {}
    aa = "%.3f" % round(a, 4)
    for u in uu:
      i = integrate.quad( Fua,u,integrate.Inf,args=(a) )
      v = "%.10f" % round(u, 9)
      if i[0] >=0.0001:
        uval[v] = i[0]
        ll = "INSERT INTO wua VALUES(%f,%f,%f);" % ( a, u, i[0] )
        c.execute(ll)    
    wuadata[aa] = uval
  conn.commit()  
  c.close()
  ##print "wuadata[0.2] = %s" % wuadata['0.200']
  return ( wuadata )
  
if __name__ == '__main__':
  import cProfile
  wuadata = generaWua()
#  kk = wuadata['0.200'].keys()
#  kk.sort()
#  for k in kk:
#   #print "k=%s,val=%s" % ( k,wuadata['0.200'][k] )     
  #conn = sqlite3.connect('data.sqlite')
  #c = conn.cursor()  
  #encuentraWua( c,  0.04, 0.00054 )
  # cProfile.run('generaWua()') 
  cProfile.run('diez()') 
  #c.close()
  #u = 0.000012
  #print u
  #limites(u)
  
  #u = 0.00000092
  #print u
  #limites(u)
  
  #u = 1234.54674
  #print u  
  #limites(u)
  
